package com.hxzy.controller.admin;

import com.github.tobato.fastdfs.domain.conn.TrackerConnectionManager;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import com.github.tobato.fastdfs.domain.upload.ThumbImage;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Api(tags = "fastdfs文件上传API")
@RestController
@RequestMapping(value = "/api/fdfs")
public class FastdfsUploadController {

    /**
     * 为了获取fastdfs服务器列表
     */
    @Autowired
    private TrackerConnectionManager  trackerConnectionManager;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig;

    /**
     * 并发整数操作
     */
    private AtomicInteger  atomicInteger=new AtomicInteger(0);



    @ApiOperation(value = "图片上传")
    @PostMapping(value = "/upload/image")
    public R  uploadImage(MultipartFile file) throws IOException {
        //文件不能为空
        if(file.isEmpty()){
            return R.build(AckCode.FILE_NOT_EMPTY);
        }

        List<String> stringList = Arrays.asList(".png", ".jpg",".jpeg");

        //上传原始的文件名
        String oriFile= file.getOriginalFilename();
        //取得文件后缀名
        String extend= FilenameUtils.getExtension(oriFile).toLowerCase();
        if(!stringList.contains("."+extend)){
            return R.build(AckCode.UPLOAD_TYPE_ERROR_IMAGE);
        }

        //设定文件详情(key,value)
        Set<MetaData> metaDataSet = new HashSet<>();
        metaDataSet.add(new MetaData("fileName", oriFile));
        metaDataSet.add(new MetaData("size", file.getSize()+""));
        metaDataSet.add(new MetaData("mime-type", file.getContentType()));

        //上传图片
        FastImageFile  fastImageFile=new FastImageFile(file.getInputStream(),file.getSize(),extend,metaDataSet);
        StorePath  storePath=this.storageClient.uploadImage(fastImageFile);

        //文件上传失败了
        if(storePath==null){
            return R.build(AckCode.FILE_UPLOAD_FAILED);
        }

        String url=storePath.getFullPath();


        String serverUrl="http://"+this.getServiceName()+"/";


        Map<String,Object> data=new HashMap<>();
        //上传的文件名
        data.put("fileName",oriFile);
        data.put("url",serverUrl+url);

        return R.okHasData(data);
    }

    /**
     * 得到fastdfs服务器的名称
     * @return
     */
    private String getServiceName(){
        String serverUrl="";
        List<String> trackerList = this.trackerConnectionManager.getTrackerList();
        if(trackerList.size()>1){
            //轮询的代码
            int current = this.atomicInteger.getAndIncrement();
            int index=  current %  trackerList.size();
            serverUrl= trackerList.get(index);

        }else{
            serverUrl= trackerList.get(0);
        }

        //替换端口 22122 换成 8888
       return  serverUrl.replace("22122","8888");
    }


    @ApiOperation(value = "图片上传并生成缩略图")
    @PostMapping(value = "/upload/imageandthumb")
    public R  uploadImageAndCrtThumbImage(MultipartFile file) throws IOException {
        //文件不能为空
        if(file.isEmpty()){
            return R.build(AckCode.FILE_NOT_EMPTY);
        }

        List<String> stringList = Arrays.asList(".png", ".jpg",".jpeg");

        //上传原始的文件名
        String oriFile= file.getOriginalFilename();
        //取得文件后缀名
        String extend= FilenameUtils.getExtension(oriFile).toLowerCase();
        if(!stringList.contains("."+extend)){
            return R.build(AckCode.UPLOAD_TYPE_ERROR_IMAGE);
        }

        //设定文件详情(key,value)
        Set<MetaData> metaDataSet = new HashSet<>();
        metaDataSet.add(new MetaData("fileName", oriFile));
        metaDataSet.add(new MetaData("size", file.getSize()+""));
        metaDataSet.add(new MetaData("mime-type", file.getContentType()));

        //定义缩略图大小
       ThumbImage  thumbImage= new ThumbImage(this.thumbImageConfig.getWidth(), this.thumbImageConfig.getWidth());

        //上传图片
        FastImageFile  fastImageFile=new FastImageFile(file.getInputStream(),file.getSize(),extend,metaDataSet,thumbImage);
        StorePath  storePath=this.storageClient.uploadImage(fastImageFile);

        //文件上传失败了
        if(storePath==null){
            return R.build(AckCode.FILE_UPLOAD_FAILED);
        }

        String url=storePath.getFullPath();

        //服务器地址
        String serverUrl="http://"+this.getServiceName()+"/";

        Map<String,Object> data=new HashMap<>();
        //上传的文件名
        data.put("fileName",oriFile);
        data.put("url",serverUrl+url);

        //得到缩略图前缀名 _150x150
        String   prev=thumbImage.getPrefixName();
        // url="group01/00/00/fdsfaffasfsafsafsadfasf.jpg
        //url_thum="group01/00/00/fdsfaffasfsafsafsadfasf_150x150.jpg
        String fileNameDotPrev=url.substring(0,url.lastIndexOf("."));
        fileNameDotPrev+=prev+"."+extend;

        data.put("url_thumb",serverUrl+fileNameDotPrev);

        return R.okHasData(data);
    }


}
